<template>
  <div>
    <atom-sticky><atom-search-input placeholder="请输入股票名称" @click.stop="toSearch" /></atom-sticky>
    <atom-tabs v-model="active" sticky offsetTop="3.6rem">
      <atom-tab :title="`${limitDate}涨停`">
        <atom-notice-bar background="rgba(51,102,255,0.10)" color="#3366FF" closeable
          >更新于{{ limitDate }} 15:30，交易日15:30后刷新当日数据</atom-notice-bar
        >
        <template v-if="limitupData.length || footerOption.type === 'loading'">
          <atom-stock-list
            :table-data="limitupData"
            :columns="limitupColumns"
            fixed-header
            offsetHeader="6.5rem"
            :footerOption="footerOption"
            @rowClick="rowClick"
            @sortChange="sortTable('limitupColumns', $event)"
          >
            <template #header-notice>
              <div class="header-notice" @click.stop="showPopup('zhangting.settx')">
                提醒<img class="icon-sys" :src="iconSys" alt="" />
              </div>
            </template>
            <template #body-notice="{ row }">
              <atom-switch
                @click.stop
                v-model="row.notice"
                @change="changeNotice(row.stockCode, limitupData, $event)"
              />
            </template>
          </atom-stock-list>
        </template>
        <atom-empty type="search" v-else />
      </atom-tab>
      <atom-tab title="高度活跃">
        <template v-if="highlyActiveData.length || footerOption.type === 'loading'">
          <atom-stock-list
            :table-data="highlyActiveData"
            :columns="highColumns"
            fixed-header
            :footerOption="footerOption"
            offsetHeader="6.5rem"
            @rowClick="rowClick"
            @sortChange="sortTable('highColumns', $event)"
          >
            <template #header-notice>
              <div class="header-notice" @click.stop="showPopup('active.settx')">
                提醒<img class="icon-sys" :src="iconSys" alt="" />
              </div>
            </template>
            <template #body-notice="{ row }">
              <atom-switch
                @click.stop
                v-model="row.notice"
                @change="changeNotice(row.stockCode, highlyActiveData, $event)"
              />
            </template>
          </atom-stock-list>
        </template>
        <atom-empty type="search" v-else />
      </atom-tab>
      <atom-tab title="已关注">
        <template v-if="noticeData.length || footerOption.type === 'loading'">
          <atom-stock-list
            :table-data="noticeData"
            :columns="noticeColumns"
            fixed-header
            :footerOption="footerOption"
            offsetHeader="6.5rem"
            @rowClick="rowClick"
            @sortChange="sortTable('noticeColumns', $event)"
          >
            <template #header-notice>
              <div class="header-notice" @click.stop="showPopup('follow.settx')">
                提醒<img class="icon-sys" :src="iconSys" alt="" />
              </div>
            </template>
            <template #body-notice="{ row }">
              <atom-switch @click.stop v-model="row.notice" @change="changeNotice(row.stockCode, noticeData, $event)" />
            </template>
          </atom-stock-list>
        </template>
        <atom-empty type="search" v-else />
      </atom-tab>
    </atom-tabs>
    <atom-popup v-model="isShowPopup" round position="bottom" style="height: 65%" closeable get-container="body">
      <PopupContent :monitorStatus="monitorStatus" @closePopup="isShowPopup = false" />
    </atom-popup>
  </div>
</template>

<script>
import { reqBase } from '@/apis/index.js';
import PopupContent from '@/components/ztjk/PopupContent.vue';
import { errorReport, jumpToFenShi, convertNumber, formatDate, DatePlus } from '@/scripts/tools.js';
import sortDataMixins from '@/mixins/sortDataMixins.js';
import limitupMixins from '@/mixins/limitupMixins.js';
import config from '@/config/index.ts';
import { ztjkLimitupColumn, ztjkHighColumn, ztjkNoticeColumn } from '@/scripts/tableColumn.js';
import { Dialog } from '@atom/atom-ui';

const {
  stat: { oldPageId },
} = config;
export default {
  components: {
    PopupContent,
  },
  mixins: [sortDataMixins, limitupMixins],
  data() {
    return {
      footerOption: {
        type: 'loading',
      },
      // 涨停配置
      limitupColumns: JSON.parse(JSON.stringify(ztjkLimitupColumn)),
      // 列数据配置
      highColumns: JSON.parse(JSON.stringify(ztjkHighColumn)),
      // 关注数据配置
      noticeColumns: JSON.parse(JSON.stringify(ztjkNoticeColumn)),
      // 涨停表格数据
      limitupData: [],
      // 高度活跃表格数据
      highlyActiveData: [],
      // 已关注
      noticeData: [],
      active: 0,
      isShowPopup: false,
      monitorStatus: [],
      limitDate: '',
      iconSys:
        '//i.thsi.cn/staticS3/mobileweb-upload-static-server.img/m/atom/8e2a0ffa-c51e-450c-a29e-261ea996ae5b.png',
    };
  },
  methods: {
    rowClick(params) {
      const { stockCode, market } = params.row;
      jumpToFenShi(stockCode, market);
    },
    changeNotice(stockCode, tableData, status) {
      const op = status ? 'setStockMonitor' : 'cancelStockMonitor';
      if (status) {
        let noticeLen = 0;
        this.noticeData.forEach(item => {
          item.notice && noticeLen++;
        });
        const MAXNUM = 30;
        if (noticeLen >= MAXNUM) {
          Dialog.alert({
            title: '提示',
            message: '最多监控30只股票，请清理已关注个股再添加新的股票',
            isTextCenter: true,
            beforeClose: (action, done) => {
              tableData.find(item => {
                if (item.stockCode === stockCode) {
                  item.notice = false;
                }
              });
              done();
            },
          });
          return;
        }
      }
      reqBase({ op, stockCode }).catch(err => {
        this.$toast('关注失败');
        errorReport({
          name: `涨停监控关注接口报错，${err.name}`,
          message: err.message,
          stack: err.stack,
        });
      });
    },
    getLimitup() {
      this.footerOption.type = 'loading';
      this.getLbgg({ noticeData: this.noticeData, tableDataName: 'limitupData', columnsName: 'limitupColumns' }, () => {
        const date = this.limitupData?.[0]?.date || '';
        const dateStr = formatDate(date, '/');
        this.limitDate = new DatePlus(dateStr).format('MM/dd');
        this.footerOption.type = '';
      });
    },
    getBase() {
      this.footerOption.type = 'loading';
      reqBase({ op: 'getEstimateLimitUpStock' })
        .then(res => {
          const { preLimitStockList, monitorStockList, monitorStatus } = res.data;
          this.monitorStatus.push(...monitorStatus);
          const highlyActiveData = [];
          const noticeData = [];
          preLimitStockList.forEach(item => {
            highlyActiveData.push({
              stockCode: item.stockCode,
              stockName: item.stockName,
              rise: item.currentIncrease,
              gene: item.limitGene,
              market: item.market,
              fiveMinRise: item.fiveMinRise,
              sellForce: convertNumber(item.sellPower, 'tenThousand') + '手',
              buyForce: convertNumber(item.buyPower, 'tenThousand') + '手',
              maxRise: item.todayMaxRise,
              notice: !!monitorStockList.find(i => i.stockCode === item.stockCode),
            });
          });
          monitorStockList.forEach(item => {
            noticeData.push({
              stockCode: item.stockCode,
              stockName: item.stockName,
              rise: item.change,
              price: item.price,
              notice: true,
              market: item.market,
            });
          });
          this.limitupData.forEach(item => {
            item.notice = !!monitorStockList.find(i => i.stockCode === item.stockCode);
          });
          this.highlyActiveData = highlyActiveData;
          this.noticeData = noticeData;
          this.sortTable('highColumns');
          this.sortTable('noticeColumns');
        })
        .catch(err => {
          errorReport({
            name: `涨停监控接口报错，${err.name}`,
            message: err.message,
            stack: err.stack,
          });
        })
        .finally(() => {
          this.footerOption.type = '';
        });
    },
    sortTable(column, params) {
      const columnReflectionData = {
        limitupColumns: 'limitupData',
        highColumns: 'highlyActiveData',
        noticeColumns: 'noticeData',
      };
      const tableData = columnReflectionData[column];
      this.sortData(this[column], tableData, params);
    },
    showPopup(stat) {
      window.hxmClickStat(`${oldPageId}.${stat}`);
      this.isShowPopup = true;
    },
    toSearch() {
      this.$router.push({
        path: '/search',
        query: {
          type: 'ztjk',
          screenMode: window.getParam('screenMode'),
        },
      });
    },
  },
  activated() {
    this.getLimitup();
    this.getBase();
  },
  watch: {
    active(nval) {
      const options = {
        0: 'zhangting',
        1: 'active',
        2: 'follow',
      };
      window.hxmClickStat(`${oldPageId}.monitor.${options[nval]}`);
      if (nval !== 0) {
        this.getBase();
      } else {
        this.getLimitup();
      }
    },
  },
};
</script>
<style lang="less" scoped>
.header-notice {
  display: flex;
  align-items: center;
  .icon-sys {
    width: 36px;
    height: 36px;
    margin-left: 4px;
  }
}
</style>
